package com.bawei.common.mvi

import android.os.Bundle
import androidx.databinding.ViewDataBinding
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import com.bawei.common.base.BaseActivity
import com.bawei.common.event.CustomEvent
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

/**
 * Author: Jason Zhang
 * Date: 2024/8/19
 * Desc: MVI模式下的BaseActivity
 */
abstract class BaseMviActivity<T: ViewDataBinding>: BaseActivity<T>() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        //初始化数据
        initData()
        //更新UI
        updateUi()
        //注册EventBus
        EventBus.getDefault().register(this)
    }

    //定义一个接收EventBus消息的方法
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun receiveEvent(event: CustomEvent){
        if (event != null && event.target == this::class.java.simpleName){
            handEvent(event)
        }
    }

    //处理EventBus消息
    open fun handEvent(event: CustomEvent){

    }

    override fun onDestroy() {
        EventBus.getDefault().unregister(this)
        super.onDestroy()
    }

    private fun initData(){
        //启动协程给ViewModel发送意图Intent
        lifecycleScope.launch {
            sendViewIntent()
        }
    }

    private fun updateUi(){
        //启动协程更新UI
        lifecycleScope.launch {
            //当Activity处于STARTED状态时接收状态更新UI
            lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED){
                collectUiState()
            }
        }
    }

    open suspend fun sendViewIntent(){

    }

    open suspend fun collectUiState(){

    }

}